#include "DebugOutputWidget.h"
#include <QtWidgets>
#include <QtMessageHandler>

DebugOutputWidget::DebugOutputWidget(QWidget* parent)
    : QWidget{parent}
{
    QVBoxLayout* layout = new QVBoxLayout(this);
    outputTextEdit = new QTextEdit(this);
    outputTextEdit->setReadOnly(true);
    layout->addWidget(outputTextEdit);

    setWindowTitle("Debug Output Widget");
    resize(400, 400);
}

void DebugOutputWidget::appendDebugMessage(const QString& message, const QColor& color)
{
    QTextCharFormat format;
    format.setForeground(color);

    QTextCursor cursor(outputTextEdit->textCursor());
    cursor.movePosition(QTextCursor::End);
    outputTextEdit->setTextCursor(cursor);

    cursor.insertText(message + "\n", format);
    outputTextEdit->mergeCurrentCharFormat(format);
}

DebugOutputWidget& DebugOutputWidget::instance()
{
    static DebugOutputWidget widget;
    return widget;
}

// 格式化输出调试信息
void CustomMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message)
{
    Q_UNUSED(context)

    QString formattedMessage;
    QColor color;

    switch (type) {
        case QtDebugMsg:
            formattedMessage = QString("Debug: %1").arg(message);
            color = QColor("black");   // 设置调试信息的颜色为黑色
            break;
        case QtInfoMsg:
            formattedMessage = QString("Info: %1").arg(message);
            color = QColor("blue");   // 设置信息信息的颜色为蓝色
            break;
        case QtWarningMsg:
            formattedMessage = QString("Warning: %1").arg(message);
            color = QColor("orange");   // 设置警告信息的颜色为橙色
            break;
        case QtCriticalMsg:
            formattedMessage = QString("Critical: %1").arg(message);
            color = QColor("red");   // 设置关键信息的颜色为红色
            break;
        case QtFatalMsg:
            formattedMessage = QString("Fatal: %1").arg(message);
            color = QColor("purple");   // 设置致命信息的颜色为紫色
            abort();
        default: break;
    }

    DebugOutputWidget::instance().appendDebugMessage(formattedMessage, color);
}
